// import { useState } from "react";
import { useReducer } from "react";
//useReducer用于处理数组或者对象等复杂状态
const initState = { count: -1 };
type StateType = typeof initState;
const initFn = (state: StateType) => {
  console.log("初始化函数");

  return Math.random() > 0.5 ? state : { count: 0 };
};
// 默认不执行reducer 通过dispatch触发reducer
const reducer = (state: StateType, action: { type: "add" | "sub" }) => {
  switch (action.type) {
    case "add":
      return { count: state.count + 1 };
    case "sub":
      return { count: state.count - 1 };
    default:
      return state;
  }
};
const UseReducerFC = () => {
  // useReducer第二个参数是默认值
  // useReducer第三个参数是可选的 初始化函数
  const [state, dispatch] = useReducer(reducer, initState, initFn);
  return (
    <div>
      <button onClick={() => dispatch({ type: "add" })}>+1</button>
      <button onClick={() => dispatch({ type: "sub" })}>-1</button>
      <p>{state.count}</p>
    </div>
  );
};

export default UseReducerFC;
